package labox.innovation.gameserver.taskmanager;

import java.util.Map;
import java.util.NoSuchElementException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javolution.util.FastMap;
import labox.innovation.config.Config;
import labox.innovation.gameserver.GameTimeController;
import labox.innovation.gameserver.model.actor.L2Character;
import labox.innovation.gameserver.timer.Timer;

/**
 * @author la2 Lets drink to code!
 */
public class DecayTaskManager implements Runnable {

	protected static final Logger _log = LoggerFactory.getLogger(DecayTaskManager.class.getName());

	protected Map<L2Character, Integer> _decayTasks = new FastMap<L2Character, Integer>();

	public static final int RAID_BOSS_DECAY_TIME = 30;

	public static final int ATTACKABLE_DECAY_TIME = 20;

	private DecayTaskManager() {
		new Timer(2000, true, this).start();
	}

	public static DecayTaskManager getInstance() {
		return SingletonHolder._instance;
	}

	public void addDecayTask(L2Character actor) {
		_decayTasks.put(actor, GameTimeController.getGameTicks());
	}

	public void addDecayTask(L2Character actor, int ticks) {
		_decayTasks.put(actor, GameTimeController.getGameTicks() + ticks);
	}

	public void cancelDecayTask(L2Character actor) {
		try {
			_decayTasks.remove(actor);
		} catch (NoSuchElementException e) {
		}
	}

	public void run() {
		int current = GameTimeController.getGameTicks();
		int delay;
		try {
			if (_decayTasks != null) {
				for (Map.Entry<L2Character, Integer> actor : _decayTasks.entrySet()) {
					if (actor.getKey().isRaid() && !actor.getKey().isRaidMinion())
						delay = RAID_BOSS_DECAY_TIME;
					else
						delay = ATTACKABLE_DECAY_TIME;

					if (current - actor.getValue() > delay) {
						actor.getKey().onDecay();
						_decayTasks.remove(actor.getKey());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			_log.error("DecayTaskManager error", Config.SERVER_ID, e);
		}
	}

	@Override
	public String toString() {
		String ret = "============= DecayTask Manager Report ============\r\n";
		ret += "Tasks count: " + _decayTasks.size() + "\r\n";
		ret += "Tasks dump:\r\n";

		Long current = System.currentTimeMillis();
		for (L2Character actor : _decayTasks.keySet()) {
			ret += "Class/Name: " + actor.getClass().getSimpleName() + "/" + actor.getName() + " decay timer: " + (current - _decayTasks.get(actor)) + "\r\n";
		}

		return ret;
	}

	/**
	 * <u><b><font color="FF0000">Read only</font></b></u>
	 */
	public Map<L2Character, Integer> getTasks() {
		return _decayTasks;
	}

	@SuppressWarnings("synthetic-access")
	private static class SingletonHolder {
		protected static final DecayTaskManager _instance = new DecayTaskManager();
	}
}
